package org.numb.common.i18n;

import static org.numb.common.i18n.ErrorCode.INTERNAL_ERROR_DEFAULT_MESSAGE;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.stereotype.Component;

@Component
public class MessageProcessor {

    private static final Logger LOGGER = LoggerFactory.getLogger(MessageProcessor.class);

    @Resource
    private ResourceBundleMessageSource messageSource;


    public String getMessage(HttpServletRequest request, String msgCode, Object... params) {
        if (request == null || msgCode == null) {
            throw new IllegalArgumentException("request or message code is null!");
        }
        try {
            return messageSource.getMessage(msgCode, params, request.getLocale());
        } catch (NoSuchMessageException exception) {
            LOGGER.error("can not find the message of the message code of {}", msgCode);
            return messageSource.getMessage(INTERNAL_ERROR_DEFAULT_MESSAGE, params, request.getLocale());
        }
    }
}
